package com.atguigu.servlet;

import com.atguigu.domain.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.code.kaptcha.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author dl
 * @create 2020-04-21-22:04
 */
@WebServlet(name = "UserServlet" , urlPatterns = "/user")
public class UserServlet extends BaseServlet {

	private UserService userService = new UserServiceImpl();

	/**
	 * login method
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		String username = req.getParameter("username");
//		String password = req.getParameter("password");
//		User user = userService.userLogin(new User(null, username, password, null));
		User requestUser = WebUtils.map2Bean(req, new User());
		User user = userService.userLogin(requestUser);
		if (user != null) {
			// login success redirect to login_success.jsp
			req.getSession().setAttribute("user",user);
			resp.sendRedirect(req.getContextPath() + "/pages/user/login_success.jsp");
//			resp.sendRedirect(req.getContextPath() + "/pages/user/login_success.jsp");
		}else {
			// login failed
			req.setAttribute("msg","用户名或密码错误");
			req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
//			req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
		}
	}

	/**
	 * register method
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 之前验证token刷新原因 原因是 请求转发 重新加载页面
		/*	try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
//		String username = req.getParameter("username");
//		String password = req.getParameter("password");
//		String email = req.getParameter("email");
		User user = WebUtils.map2Bean(req, new User());

		String pageToken = req.getParameter("token");
		// 从session中取出token
		HttpSession session = req.getSession();
		String sessionToken = (String)session.getAttribute("token");

		boolean flag = false;
		System.out.println("pageToken " + pageToken);
		System.out.println("sessionToken " + sessionToken);
		if (pageToken != null && sessionToken != null) {
			if (sessionToken.equals(pageToken)) {
				session.removeAttribute("token");
				// 验证验证码是否正确
				String code = req.getParameter("code");
				String sessionCode = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
				if (!sessionCode.equals(code)) {
					// 验证码不正确
					// forward to the regist.jsp and show register failed
					req.setAttribute("msg","验证码错误");
					req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
					// return 不再往下执行
					return;
				}
				flag = userService.userRegister(user);
				System.out.println("用户注册成功");
			}
		}
		if (flag) {
			// register success to the regist_success.jsp
			resp.sendRedirect(req.getContextPath() + "/pages/user/regist_success.jsp");
		}else {
			// forward to the regist.jsp and show register failed
			req.setAttribute("msg","用户名已存在");
			req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
		}
	}

	/**
	 * determine if the user name exists
	 * use ajax
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void existsName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		boolean b = userService.existsName(username);
		if (b) {
			//TODO 返回结果应该如何进行返回
			resp.getWriter().write("<span style='color:green'>用户名可用</span>");
		}else {
			resp.getWriter().write("<span style='color:red'>用户名已存在</span>");
		}
	}

	/**
	 * user logout
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 让session失效
		req.getSession().invalidate();
		// 返回首页
		resp.sendRedirect(req.getContextPath() + "/index?method=pageByPrice");
	}
}
